package cn.tedu.dao;

import cn.tedu.entity.User;
import cn.tedu.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {

    public User login(String username, String password) {
        try (Connection conn = DBUtils.getConn()){
            String sql = "select id from webuser where username=? and password=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                int id = rs.getInt(1);
                return new User(id,username,password);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Boolean reg(String username, String password) {
        try (Connection conn = DBUtils.getConn()){
            String sql = "select id from webuser where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                System.out.println("用户名已存在!");
                return false;
            }else{
                String sq = "insert into webuser values(null,?,?)";
                PreparedStatement pss = conn.prepareStatement(sq);
                pss.setString(1,username);
                pss.setString(2,password);
                if(pss.executeUpdate()==1)
                    return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
